package io.iec.edp.caf.msu.client.discovery;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.msu.api.MsuService;
import io.iec.edp.caf.msu.api.client.ServiceDiscovery;
import io.iec.edp.caf.msu.api.entity.GspAppServerInstance;
import io.iec.edp.caf.msu.api.server.MsuServiceRegistry;
import io.iec.edp.caf.msu.client.exception.ServiceUnitNotFoundException;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class DbDiscoveryImpl implements ServiceDiscovery{


    @Override
    public String discover(String serviceUnitName, HashMap<String, String> eventContext) {
        var suService = SpringBeanUtils.getBean(MsuService.class);
        List<GspAppServerInstance> appservers =  suService.getGspAppServerInfoBySu(serviceUnitName);

        if (appservers.size() == 0) {
            log.error("db discover:RPC remote Not Found GspAppServerInstance by SU:"+serviceUnitName);
            throw new ServiceUnitNotFoundException("db discover:current su:"+serviceUnitName+"is not available");
        }
        var baseurl = appservers.get(0).getAppUrl().length() == 0 ? "http://" + appservers.get(0).getIp() + ":" + appservers.get(0).getPort() : appservers.get(0).getAppUrl();

        if(baseurl==null || baseurl.length()==0){
            log.error("db discover:RPC remote Not Found GspAppServerInstance by SU:"+serviceUnitName);
            throw new ServiceUnitNotFoundException("db discover:current su:"+serviceUnitName+"is not available");
        }
        return baseurl;
    }

    @Override
    public List<String> discoverAll(String serviceUnitName, HashMap<String, String> eventContext) {

        //todo
        return new ArrayList<String>();
    }
}
